package com.dudao.modules.sms.controller;

import com.dudao.common.annotation.LogOperation;
import com.dudao.common.constant.Constant;
import com.dudao.common.page.PageData;
import com.dudao.common.utils.ExcelUtils;
import com.dudao.common.utils.IpUtils;
import com.dudao.common.utils.Result;
import com.dudao.common.validator.AssertUtils;
import com.dudao.common.validator.ValidatorUtils;
import com.dudao.common.validator.group.AddGroup;
import com.dudao.common.validator.group.DefaultGroup;
import com.dudao.common.validator.group.UpdateGroup;
import com.dudao.modules.oss.cloud.CloudStorageConfig;
import com.dudao.modules.sms.dto.SysSmsDTO;
import com.dudao.modules.sms.dto.SysSmsLogDTO;
import com.dudao.modules.sms.entity.SysSmsEntity;
import com.dudao.modules.sms.excel.SysSmsExcel;
import com.dudao.modules.sms.service.SysSmsLogService;
import com.dudao.modules.sms.service.SysSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 *
 *
 * @author Lii juliip@163.com
 * @since 1.0.0 2022-12-16
 */
@RestController
@RequestMapping("sms/syssms")
@Api(tags="发送短信")
public class SysSmsController {
    @Autowired
    private SysSmsService sysSmsService;

    @Autowired
    private SysSmsLogService sysSmsLogService;

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("sms:syssms:page")
    public Result<PageData<SysSmsDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<SysSmsDTO> page = sysSmsService.page(params);

        return new Result<PageData<SysSmsDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sms:syssms:info")
    public Result<SysSmsDTO> get(@PathVariable("id") Long id){
        SysSmsDTO data = sysSmsService.get(id);

        return new Result<SysSmsDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sms:syssms:save")
    public Result save(@RequestBody SysSmsDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysSmsService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sms:syssms:update")
    public Result update(@RequestBody SysSmsDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysSmsService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sms:syssms:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        sysSmsService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sms:syssms:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysSmsDTO> list = sysSmsService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, SysSmsExcel.class);
    }

    @PostMapping("emails")
    @ApiOperation("发送邮件")
    @LogOperation("发送邮件")
    public Result sendEmail(@RequestBody SysSmsEntity sysSmsEntity,HttpServletRequest request){

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        String message = sysSmsEntity.getRecipients();
        String sendNumbers = sysSmsEntity.getSendNumbers();
        String theme = sysSmsEntity.getTheme();
        String errorMsg = "";
        try {
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(sendNumbers);
            simpleMailMessage.setSubject(theme);
            simpleMailMessage.setText(message);

            mailSender.send(simpleMailMessage);
        } catch (MailException e) {
            e.printStackTrace();
            errorMsg = e.toString();
        } finally {
            SysSmsLogDTO sysSmsLogDTO = new SysSmsLogDTO();
            sysSmsLogDTO.setAccessData(message);
            sysSmsLogDTO.setSendNumbers(sendNumbers);
            sysSmsLogDTO.setTheme(theme);
            sysSmsLogDTO.setCreateDate(new Date());
            sysSmsLogDTO.setErrorMsg(errorMsg);
            if (errorMsg.equals("")){
                sysSmsLogDTO.setState("发送成功");
            }else{
                sysSmsLogDTO.setState("发送失败");
            }
            sysSmsLogDTO.setIp(IpUtils.getIpAddr(request));
            sysSmsLogService.save(sysSmsLogDTO);
        }
        return new Result();
    }

}
